package kr.co.bettersoft.usedmarketandroid.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketMember;
import kr.co.bettersoft.usedmarketandroid.domain.UsedMarketSMS;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

public class UsedMarketRest {
	String TAG = "UsedMarketRest";


	
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	// 서버 통신

	/**
	 * RestCertificationStep_1
	 *  전화번호를 보내서 인증번호 4자리를 받아온다.
	 * @return  String
	 */
	public String RestCertificationStep_1(UsedMarketSMS usedMarketSMS){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();
		
		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CERTIFICATION_CONTROLLER+"/"+CommonConstant.REQUEST_CERTIFICATION;
		JSONObject obj = new JSONObject();
		try{		 
			obj.put("phoneNumber", usedMarketSMS.getPhoneNumber());	
			obj.put("activateYn", "Y");
			obj.put("modifyDate", nowDate);
			obj.put("registerDate", nowDate);
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리
		if(!(callResult.equals("F"))){
			try {
				JSONObject jsonObject = new JSONObject(callResult);
				callResult = jsonObject.getString("result").toString(); 
			} catch (JSONException e) {
				callResult = "F";
				e.printStackTrace();
			} 
		}
		return callResult;
	}


	/**
	 * RestCertificationStep_2
	 *  전화번호, 인증번호 4자리를 보내서 승인을 받는다.
	 * @return  String
	 */
	public String RestCertificationStep_2(UsedMarketSMS usedMarketSMS){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_CERTIFICATION_CONTROLLER+"/"+CommonConstant.REQUEST_ADMISSION;
		JSONObject obj = new JSONObject();
		try{		 
			obj.put("phoneNumber", usedMarketSMS.getPhoneNumber());			// 전번
			obj.put("certificationNumber", usedMarketSMS.getCertificationNumber());	// 승인번호		
			obj.put("activateYn", "Y");
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리
		if(!(callResult.equals("F"))){
			try {
				JSONObject jsonObject = new JSONObject(callResult);
				callResult = jsonObject.getString("result").toString(); 
//				Log. d(TAG,"callResult:"+callResult);
			} catch (JSONException e) {
				callResult = "F";
				e.printStackTrace();
			} 
		}
		return callResult;
	}


	
	/**
	 * RestSelectDuplicationNickNameBeforeRegister		selectDuplicationNickNameBeforeRegister
	 * 닉네임 중복 검사
	 */
	public String RestSelectDuplicationNickNameBeforeRegister(UsedMarketMember usedMarketMember){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_MEMBER_CONTROLLER+"/"+CommonConstant.SELECT_DUPLICATION_NICK_NAME_BEFORE_REGISTER;
		JSONObject obj = new JSONObject();
		try{		 
			obj.put("phoneNumber", usedMarketMember.getPhoneNumber());
			obj.put("nickName", usedMarketMember.getNickName());
			obj.put("activateYn", "Y");
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);
		
		// 서버 호출 결과 처리
		if(!(callResult.equals("F"))){
			try {
				JSONObject jsonObject = new JSONObject(callResult);		
				try{
					callResult = (jsonObject.getString("totalCount"));				 
				}catch(Exception e){
					callResult = "F";
				}
			} catch (JSONException e) {
				callResult = "F";
				e.printStackTrace();
			} 
		}
		// 서버 호출 결과 처리는 외부에서.
		return callResult;
	}
	
	
	
//	/**
//	 * RestUserRegisterCheck
//	 *  서버에 저장되어 있는지 확인.   -- 사용 안함. 서버에서 정보 가져와서 확인 후 분기 처리.
//	 * @return  String
//	 */
//	public String RestUserRegisterCheck(UsedMarketSMS usedMarketSMS){
//
//		CommonUtil commonUtil = new CommonUtil();
//		String nowDate = commonUtil.getNowDate();
//
//		// 파라미터 셋팅
//		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_MEMBER_CONTROLLER+"/"+CommonConstant.SELECT_DUPLICATION;
//		JSONObject obj = new JSONObject();
//		try{		 
//			obj.put("phoneNumber", usedMarketSMS.getPhoneNumber());
//			obj.put("activateYn", "Y");
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//		String inputJson = obj.toString();
//
//		// 서버호출 메소드 실행
//		String callResult = callServerMethod(fullUrl, inputJson);
//		
//		// 서버 호출 결과 처리는 외부에서.
//		return callResult;
//	}

	/**
	 * selectMemberFromApp	사용자 정보를 가져 온다.	phoneNumber
	 */
	public String RestSelectMemberFromApp(UsedMarketMember usedMarketMember){

//		CommonUtil commonUtil = new CommonUtil();
//		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_MEMBER_CONTROLLER+"/"+CommonConstant.SELECT_MEMBER_FROM_APP;
		JSONObject obj = new JSONObject();
		try{		 
			obj.put("phoneNumber", usedMarketMember.getPhoneNumber());
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리는 외부에서.
		return callResult;
	}
	
	
	/**
	 * RestRegisterMemberToServer
	 *  서버에 멤버 가입 한다.
	 * @return  String
	 */
	public String RestRegisterMemberToServer(UsedMarketMember usedMarketMember){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_MEMBER_CONTROLLER+"/"+CommonConstant.REGISTER_MEMBER;
		JSONObject obj = new JSONObject();
		try{		 
			
			obj.put("phoneNumber", usedMarketMember.getPhoneNumber());
			obj.put("password",usedMarketMember.getPassword());	
			obj.put("nickName", usedMarketMember.getNickName());
			obj.put("email", usedMarketMember.getEmail());	
			
			obj.put("birthday", "");	
			obj.put("gender", "");
			obj.put("comment", "");	
			obj.put("profileImage", "");	
			obj.put("thumbnailLarge", "");	
			obj.put("thumbnailSmall", "");	
			obj.put("deviceType", "AS");
			obj.put("pushId", "");
			obj.put("notificationYn", "Y");
			obj.put("mileage", "100");
			obj.put("grade", "5");
			obj.put("restrictionYn", "Y");
			obj.put("activateYn", "Y");
			obj.put("modifyDate", nowDate);
			obj.put("registerDate", nowDate);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리
		if(!(callResult.equals("F"))){
			try {
				JSONObject jsonObject = new JSONObject(callResult);		
				try{
					callResult = (jsonObject.getString("result"));				 
				}catch(Exception e){
					callResult = "F";
				}
			} catch (JSONException e) {
				callResult = "F";
				e.printStackTrace();
			} 
		}
		return callResult;
	}
	
	/**
	 * RestUpdateMember
	 *   updateMember	사용자 정보를 수정 한다.
	 * @return  String
	 */
	public String RestUpdateMemberFromApp(UsedMarketMember usedMarketMember){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_MEMBER_CONTROLLER+"/"+CommonConstant.UPDATE_MEMBER_FROM_APP;
		JSONObject obj = new JSONObject();
		try{		 
			obj.put("phoneNumber", usedMarketMember.getPhoneNumber());
			obj.put("password",usedMarketMember.getPassword());	
			obj.put("nickName", usedMarketMember.getNickName());
			obj.put("email", usedMarketMember.getEmail());	
			obj.put("birthday", "");	
			obj.put("gender", "");
			obj.put("comment", "");	
			obj.put("profileImage", "");	
			obj.put("thumbnailLarge", "");	
			obj.put("thumbnailSmall", "");	
			obj.put("deviceType", "AS");
			obj.put("pushId", "");
			obj.put("notificationYn", "Y");
			obj.put("mileage", "100");
			obj.put("grade", "5");
			obj.put("restrictionYn", "Y");
			obj.put("activateYn", "Y");
			obj.put("modifyDate", nowDate);
//			obj.put("registerDate", nowDate);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리
		if(!(callResult.equals("F"))){
			try {
				JSONObject jsonObject = new JSONObject(callResult);		
				try{
					callResult = (jsonObject.getString("result"));				 
				}catch(Exception e){
					callResult = "F";
				}
			} catch (JSONException e) {
				callResult = "F";
				e.printStackTrace();
			} 
		}
		return callResult;
	}
	

	/**
	 * RestUpdateMyGCMtoServer
	 *  서버에 gcm 아이디 업뎃한다
	 * @return  String
	 */
	public String RestUpdateMyGCMtoServer(UsedMarketMember usedMarketMember){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_MEMBER_CONTROLLER+"/"+CommonConstant.UPDATE_PUSH_ID;
		JSONObject obj = new JSONObject();
		try{		 
			obj.put("phoneNumber", usedMarketMember.getPhoneNumber());	
			obj.put("pushId", usedMarketMember.getPushId());	
			obj.put("activateYn", "Y");
			obj.put("modifyDate", nowDate);							
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리
		if(!(callResult.equals("F"))){
			try {
				JSONObject jsonObject = new JSONObject(callResult);
				callResult = jsonObject.getString("result").toString(); 
//				Log. d(TAG,"callResult:"+callResult);
			} catch (JSONException e) {
				e.printStackTrace();
				callResult="F";
			} 
		}
		return callResult;
	}

	
	
	/**
	 * RestUpdateDeactivate
	 *   멤버 탈퇴
	 * @return  String
	 */
	public String RestUpdateDeactivate(UsedMarketMember usedMarketMember){

		CommonUtil commonUtil = new CommonUtil();
		String nowDate = commonUtil.getNowDate();

		// 파라미터 셋팅
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_MEMBER_CONTROLLER+"/"+CommonConstant.UPDATE_DEACTIVATE;
		JSONObject obj = new JSONObject();
		try{		 
			obj.put("phoneNumber", usedMarketMember.getPhoneNumber());	
			obj.put("activateYn", "N");
			obj.put("modifyDate", nowDate);							
		}catch(Exception e){
			e.printStackTrace();
		}
		String inputJson = obj.toString();

		// 서버호출 메소드 실행
		String callResult = callServerMethod(fullUrl, inputJson);

		// 서버 호출 결과 처리
		if(!(callResult.equals("F"))){
			try {
				JSONObject jsonObject = new JSONObject(callResult);
				callResult = jsonObject.getString("result").toString(); 
				Log. d(TAG,"callResult:"+callResult);
			} catch (JSONException e) {
				e.printStackTrace();
				callResult="F";
			} 
		}
		return callResult;
	}

	
	
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	/**
	 * 친구에게 추천하기
	 *    sendRecommendation	친구들에게 추천 메시지를 전송한다.
	 *     usedMarketRecommendationController	sendRecommendation
	 */
	public String RestSendRecommendation(List<UsedMarketSMS> usedMarketSMSList){
		
		String returnStr = "";
//		CommonUtil commonUtil = new CommonUtil();
//		String nowDate = commonUtil.getNowDate();
		// 파라미터 셋팅 	
		String fullUrl = CommonConstant.serverNames+"/"+CommonConstant.USED_MARKET_RECOMMENDATION_CONTROLLER+"/"+CommonConstant.SEND_RECOMMENDATION;

		try {
			JSONArray parameterJsonArray = new JSONArray();
			
			for(int i=0; i<usedMarketSMSList.size(); i++){
				UsedMarketSMS usedMarketSMS = usedMarketSMSList.get(i);
				JSONObject parameterJsonObject = new JSONObject();				
				parameterJsonObject.put("phoneNumber", usedMarketSMS.getPhoneNumber());
				parameterJsonObject.put("sender", usedMarketSMS.getSender());
				parameterJsonArray.put(parameterJsonObject.toString());		 // jsonArray 에 jsonObject 를 담아서 서버로 리스트를 보낼때는 jsonObject 그대로 넣지 않고 toString() 으로 변환하여 담는다
			}
//			Log.d(TAG,"parameterJsonArray.toString():"+parameterJsonArray.toString());
			returnStr = callServerMethod(fullUrl, parameterJsonArray.toString());		// 서버로부터 결과 받지 않음
		} catch(Exception e) {
			e.printStackTrace();
			returnStr = "F";
		}
		
		return returnStr;
	}
	
	
	
	
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	


	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	

	// 공용 서버 호출 메소드
	public String callServerMethod(String fullUrl, String inputJson){
		String callResult = "";
		try{
			URL postUrl = new URL(fullUrl);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
			connection.setConnectTimeout(CommonConstant.serverConnectTimeOut);
			connection.setDoOutput(true);
			connection.setInstanceFollowRedirects(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type", "application/json");

			OutputStream os = connection.getOutputStream();		// 여기서 타임아웃이 발생하는 경우가 있음
			os.write(inputJson.getBytes("UTF-8"));
			os.flush();
			
			int responseCode = connection.getResponseCode();
			InputStream in =  connection.getInputStream();
			if(responseCode==200 || responseCode==204){
				// 결과를 처리.
				BufferedReader reader = new BufferedReader(new InputStreamReader(in), 8192);
				StringBuilder builder = new StringBuilder();
				String line =null;
				try {
					while((line=reader.readLine())!=null){
						builder.append(line).append("\n");
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				callResult = builder.toString();
			}else{
				callResult="F";
			}
		}catch(Exception e){ 
			e.printStackTrace();
			callResult="F";
		}
		return callResult;
	}	

}
